package drds.plus.repository.berkeley.spi;

import drds.plus.executor.cursor.cursor_metadata.CursorMetaData;
import drds.plus.executor.record_codec.record.KeyValueRecordPair;
import drds.plus.executor.record_codec.record.Record;
import drds.plus.executor.row_values.AbstractRowValues;
import drds.plus.executor.row_values.RowValues;

import java.util.ArrayList;
import java.util.List;

public class KeyValuePairRowValues extends AbstractRowValues implements RowValues {

    private final KeyValueRecordPair keyValueRecordPair;
    private final int keyLength;

    public KeyValuePairRowValues(CursorMetaData cursorMeta, KeyValueRecordPair keyValueRecordPair) {
        super(cursorMeta);
        this.keyValueRecordPair = keyValueRecordPair;
        keyLength = keyValueRecordPair.getKey().getColumnNameToIndexMap().size();
    }

    public Object getObject(int index) {
        if (keyLength > index) {
            return keyValueRecordPair.getKey().getValue(index);
        } else {
            index = index - keyLength;
            return keyValueRecordPair.getValue().getValue(index);
        }
    }

    public void setObject(int index, Object value) {
        if (keyLength > index) {
            keyValueRecordPair.getKey().setValue(index, value);
        } else {
            index = index - keyLength;
            keyValueRecordPair.getValue().setValue(index, value);
        }
    }

    public List<Object> getValueList() {
        Record cr = keyValueRecordPair.getKey();
        List<Object> objectList = null;
        if (cr != null) {
            objectList = new ArrayList<Object>(keyValueRecordPair.getKey().getValueList());
        } else {
            objectList = new ArrayList<Object>();
        }
        cr = keyValueRecordPair.getValue();
        if (cr != null) {
            objectList.addAll(cr.getValueList());
        }
        return objectList;
    }

}
